GApp.Configuration = {
    list: [],
    url: '/?url=configConfiguration/descriptors'
};

(function (P) {
    
///////////////////////////////////////////////////////////////////////////////
// AREA CONFIGURATION
///////////////////////////////////////////////////////////////////////////////

    P.getDescriptor = function (id) {
        var descriptor = null;
        $.each(P.list, function (i, v) {
           if (v.id === id) {
               descriptor = P.list[i];
           } 
        });
        return descriptor;
    },
    
    P.updateTableDescriptors = function (url, doneCallback) {
         var idConfiguration = $('#idConfiguration').val ();
         
         $.ajax ({
            type: 'get',
            url: GApp.baseURL + url,
            data: { 'idConfiguration': idConfiguration }
        })
        .done (function (data) {
            var tmp = [];
            var json = JSON.parse (data);
            
            P.list.length = 0;
            
            $('#dataTables-descriptors > tbody').html ('');
            $.each(json, function (i, v) {
                tmp.push ('<tr class="odd gradeX">');
                tmp.push ('<td align="center">');
                tmp.push ('<a href="#" onclick="GApp.Configuration.modifyDescriptor (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-pencil-square fa-lg"></i></a> '); 
                tmp.push ('<a href="#" onclick="GApp.Configuration.removeDescriptor (\'' + v.id + '\')">');
                tmp.push ('<i class="fa fa-minus-square fa-lg"></i></a>');
                tmp.push ('</td>');
                tmp.push ('<td>' + v.name + '</td>');
                tmp.push ('<td>' + v.value + '</td>');
                tmp.push ('<td>' + v.order + '</td>');
                tmp.push ('</tr>');
                P.list.push (v);
            });
            
            $('#dataTables-descriptors > tbody').html (tmp.join (''));
            
            if (doneCallback) {
                doneCallback.call (this);
            }
        })
        .fail (function () {
            console.log ('ERROR: updateTableDescriptors');
        });
    },
    
    P.sendDescriptor = function (data, okCallback, errorCallback) {
        var url = ($('#descriptorIdForm').val () !== '') ? 'modifyDescriptor' : 'addDescriptor';
        var idConfiguration = $('#idConfiguration').val ();

        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configConfiguration/' + url,
            data: {
                idConfiguration: idConfiguration,
                name: data.name,
                value: data.value,
                order: data.order,
                id: data.id
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.sendRemoveDescriptor = function (data, okCallback, errorCallback) {        
        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configConfiguration/removeDescriptor',
            data: {
                id: data.id
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.validateAndCommitModal = function () {
        var errors = 0;
        var descriptor = {
            id: $('#descriptorIdForm').val () || null,
            name: $('#descriptorNameForm').val () || null,
            value: $('#descriptorValueForm').val () || null,
            order: $('#descriptorOrderForm').val ()
        };

        if (!descriptor.name || descriptor.name.length == 0) {
            $('#descriptorNameForm').parent ().addClass ('has-error');
            errors++;
        }
        else {
            $('#descriptorNameForm').parent ().removeClass ('has-error');
        }

        if (!descriptor.value || descriptor.value.length == 0) {
            $('#descriptorValueForm').parent ().addClass ('has-error');
            errors++;
        }
        else {
            $('#descriptorValueForm').parent ().removeClass ('has-error');
        }

        if (errors === 0) {
             P.sendDescriptor (descriptor, 
                 function () {
                    // OK
                    $('#descriptorModalDlg').modal ('hide');
                    P.updateTableDescriptors (P.url);
                 },
                 function () {
                    // Error
                    console.log  ('Error: validateAndCommitModal');
                 }
             );
        }
    },
    
    P.confirmFormDescriptor = function (descriptor) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>¿Quieres eliminar el descriptor seleccionado?</label>');
        form.push ('</div>');
        
        $('#descriptorModalLabel').text ('Eliminar descriptor');
        $('#descriptorAcceptModalDlg').on ('click', function () {
           P.sendRemoveDescriptor(descriptor, 
                 function () {
                    // OK
                    $('#descriptorModalDlg').modal ('hide');
                    P.updateTableDescriptors (P.url);
                 },
                 function () {
                    // Error
                    console.log  ('Error: confirmFormDescriptor');
                 }
            );
        });
        
        $('#descriptorModalBody').html (form.join (''));
        $('#descriptorModalDlg').modal ();
        $('#descriptorModalDlg').on ('hidden.bs.modal', function () {
            $('#descriptorAcceptModalDlg').off ('click');
            $('#descriptorModalDlg').off ('hidden.bs.modal');
        });
        
        if (descriptor) {
            $('#descriptorIdForm').val (descriptor.id);
        }
        
        return false;
    },
    
    P.showFormDescriptor = function (title, descriptor) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>Nombre</label>');
        form.push ('<input class="form-control" placeholder="Nombre" id="descriptorNameForm">');
        form.push ('</div>');
        form.push ('<div class="form-group">');
        form.push ('<label>Valor</label>');
        form.push ('<input class="form-control" placeholder="Valor" id="descriptorValueForm">');
        form.push ('</div>');
        form.push ('<div class="form-group">');
        form.push ('<label>Orden</label>');
        form.push ('<input class="form-control" placeholder="Orden" id="descriptorOrderForm">');
        form.push ('<input type="hidden" id="descriptorIdForm">');
        form.push ('</div>');
        
        $('#descriptorModalLabel').text (title);
        $('#descriptorAcceptModalDlg').on ('click', function () {
           P.validateAndCommitModal ();
        });
        
        $('#descriptorModalBody').html (form.join (''));
        $('#descriptorModalDlg').modal ();
        $('#descriptorModalDlg').on ('hidden.bs.modal', function () {
            $('#descriptorAcceptModalDlg').off ('click');
            $('#descriptorModalDlg').off ('hidden.bs.modal');
        });
        
        if (descriptor) {
            $('#descriptorNameForm').val (descriptor.name);
            $('#descriptorValueForm').val (descriptor.value);
            $('#descriptorOrderForm').val (descriptor.order);
            $('#descriptorIdForm').val (descriptor.id);
        }
        
        return false;
    },

    P.newDescriptor = function () {        
        return P.showFormDescriptor ('Nuevo descriptor');
    },

    P.modifyDescriptor = function (id) {
        return P.showFormDescriptor ('Modificar descriptor', P.getDescriptor (id));
    },
    
    P.removeDescriptor = function (id) {
        return P.confirmFormDescriptor (P.getDescriptor (id));
    }
} (GApp.Configuration));

if (document.URL.indexOf ('url=configConfiguration') > 0) {
    GApp.Helper.createWaitDialog ('waitingModal');
    
    $(document).ready (function () {
        GApp.Helper.showPleaseWait ();
        GApp.Configuration.updateTableDescriptors (GApp.Configuration.url, function () {
            GApp.Helper.hidePleaseWait ();
        });
    });
}
